var $div, $target, $textArea, $body, undoStep = [], redoStep = [], cache = new Map();
$(function() {
	$(document).bind("contextmenu", function(e) {
		return false;
	});
	$div = $("#report-body");
	$div.click(function(e) {
		var target = e.target;
		if (target.nodeName == "INPUT") {
			$target = $(target).parent();
			undoStep.push($(target));
		}
	});
	$body = $("body");
	$body.append(creatHideArea());
	$textArea = $("#textArea");
	$body.keydown(cellkeydown);
});
function creatHideArea() {
	var html = "<div style='position: fixed; top: -10000px; left: -10000px;'>"
			+ "<textarea id='textArea' style='overflow: hidden;'>"
			+ "</textarea></div>";
	return html;
}
function cellkeydown(event) {
	if (event.ctrlKey && event.keyCode == 86) { //复制
		$textArea.focus();
		$textArea.select();
		// 等50毫秒，keyPress事件发生了再去处理数据 
		setTimeout("dealwithData()", 50);
	} else if (event.ctrlKey && event.keyCode == 89) { //恢复
		redo();
	} else if (event.ctrlKey && event.keyCode == 90) { //撤销
		undo();
	} else {
		//暂时不处理
	}
}
function dealwithData() {
	var rowDatas = $textArea.val().split('\n');
	$textArea.blur();
	var rowNumber = $target.attr("rowHid");
	var inputObj = [];
	var $tbody = $div.find("tbody");
	for (var i = 0; i < rowDatas.length - 1; i++) {
		var colDatas = rowDatas[i].split('\t');
		var colNumber = $target.attr("colHid");
		for (var j = 0; j < colDatas.length; j++) {
			var element = $tbody.find("td[rowHid='" + rowNumber + "'][colHid='" + colNumber + "']");
			if (element.attr("readHid") && element.attr("readHid") == "false") {
				var child = element.children(":input");
				child.val(colDatas[j]);
				inputObj.push(child);
				cache.put(rowNumber+":"+colNumber, colDatas[j]);
			}
			if(element.attr("colspan")){
				colNumber = colNumber + parseInt(element.attr("colspan"));
			}else{
				colNumber++;				
			}
		}
		rowNumber++;
	}
	undoStep.splice(-1, 1, inputObj);
}
function undo() {
	var undoObj = undoStep.pop();
	redoStep.push(undoObj);
	if (undoObj.length > 1) {
		for (var i = 0; i < undoObj.length; i++) {
			undoObj[i].val("");
		}
	}
}
function redo() {
	var redoObj = redoStep.pop();
	undoStep.push(redoObj);
	if (redoObj.length > 1) {
		for (var i = 0; i < redoObj.length; i++) {
			var parent = redoObj[i].parent();
			redoObj[i].val(cache.get(parent.attr("rowHid")+":"+parent.attr("colHid")));
		}
	}
}